package com.wl.day45.biz;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.wl.day45.dao.ProductsMapper;
import com.wl.day45.dao.ResourcesMapper;
import com.wl.day45.model.Products;
import com.wl.day45.util.BusinessException;
import com.wl.day45.util.Constants;

@Service
public class ProductsBiz {
	@Resource
	private ProductsMapper productsDAO;
	@Resource
	private ResourcesMapper resourcesDAO;
	public List<Products> findAll(int page) throws BusinessException {
		try {
			return productsDAO.findAll((page-1)* Constants.PAGE_SIZE, Constants.PAGE_SIZE);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B04");
		}
	}

	public void save(Products pro) throws BusinessException {
		try {
			Date now = new Date();
			pro.getRes().setCreateTime(now);
			pro.getRes().setUpdateTime(now);
			resourcesDAO.save(pro.getRes());
			pro.setCreateTime(now);
			pro.setUpdateTime(now);
			productsDAO.insert(pro);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B01");
		}
	}

	public long findCount() throws BusinessException {
		try {
			return productsDAO.findCount();
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B06");
		}
	}

	public void delete(Products pro) throws BusinessException {
		try {
			productsDAO.deleteByPrimaryKey(pro.getProId());
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B02");
		}
	}

	public Products findById(int proId) throws BusinessException {
		try {
			return productsDAO.selectByPrimaryKey(proId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B05");
		}
	}

	public void update(Products pro) throws BusinessException {
		try {
			Date now = new Date();
			if(pro.getRes() != null){
				pro.getRes().setCreateTime(now);
				pro.getRes().setUpdateTime(now);
				resourcesDAO.save(pro.getRes());
			}
			pro.setUpdateTime(now);
			productsDAO.updateByPrimaryKeySelective(pro);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("E04B03");
		}
	}
	
}
